<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class EmployeeDepartmentPosition extends Model
{
    use HasFactory;

    protected $fillable = [
        'employee_id',
        'department_id',
        'position_id',
        'start_date',
        'end_date',
        'type',
        'reason',
        'approved_by',
        'approved_at',
        'status',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'approved_at' => 'datetime',
    ];

    /**
     * 关联员工
     */
    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

    /**
     * 关联部门
     */
    public function department(): BelongsTo
    {
        return $this->belongsTo(Department::class);
    }

    /**
     * 关联岗位
     */
    public function position(): BelongsTo
    {
        return $this->belongsTo(Position::class);
    }

    /**
     * 关联审批人
     */
    public function approver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * 检查是否为当前有效任职
     */
    public function isCurrent(): bool
    {
        return $this->status === 'active' 
            && $this->start_date <= now()
            && ($this->end_date === null || $this->end_date >= now());
    }

    /**
     * 获取任职类型标签
     */
    public function getTypeLabelAttribute(): string
    {
        $typeLabels = [
            'primary' => '主要任职',
            'temporary' => '临时任职',
            'acting' => '代理任职',
        ];

        return $typeLabels[$this->type] ?? $this->type;
    }

    /**
     * 获取状态标签
     */
    public function getStatusLabelAttribute(): string
    {
        $statusLabels = [
            'active' => '有效',
            'inactive' => '无效',
            'pending' => '待审批',
        ];

        return $statusLabels[$this->status] ?? $this->status;
    }
}
